package ro.imc.andrei.visual;

import java.awt.GridLayout;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;


import ro.imc.andrei.beans.Student;
import ro.imc.andrei.exceptions.IDException;
import ro.imc.andrei.ums.UMSDB;
import ro.imc.andrei.ums.XMLSerializer;

public class AddStudentFrame extends JFrame{
		
	//Labels
	private JLabel firstNameLabel = new JLabel("First Name");
	private JLabel lastNameLabel = new JLabel("Last Name");
	private JLabel IDLabel = new JLabel("ID");
	private JLabel studentNoLabel = new JLabel("Student Number");
	private JLabel statusLabel = new JLabel("Status");
	private JLabel facultyLabel = new JLabel("Faculty");
	
	//Text Fields
	private JTextField firstNameTextField = new JTextField();
	private JTextField lastNameTextField = new JTextField();
	private JTextField IDTextField = new JTextField();
	private JTextField studentNoTextField = new JTextField();

	//Combo Boxes
	private JComboBox<String> statusComboBox = new JComboBox<String>();
	private JComboBox<String> facultyComboBox = new JComboBox<String>();
	
	//Panel
	private JPanel mainPanel = new JPanel();
	
	//Save Button
	private JButton saveButton = new JButton("Save");
	private JButton cancelButton = new JButton("Cancel");
	
	private JFrame parent;
	
	private static int WITDH = 400;
	private static int HEIGTH = 200;
	
	public AddStudentFrame(JFrame parent){
		this.parent = parent;
		initFrame();
	}
		
	private void initFrame(){
		try{
			//Init JComboBox
			statusComboBox.removeAllItems();
			statusComboBox.addItem("Registered");
			statusComboBox.addItem("Expelled");
			statusComboBox.addItem("Enrolled");
			
			//Init Faculty Combo Box
			Class.forName("com.mysql.jdbc.Driver");
			Connection con = DriverManager.getConnection(UMSDB.getInstance().DATABASE_URL);
			Statement stmt = con.createStatement();
			ResultSet rs = stmt.executeQuery("SELECT * FROM faculty");
			
			facultyComboBox.removeAllItems();
			
			while(rs.next()){
				facultyComboBox.addItem(rs.getString("facultyName"));
			}
			
			con.close();
			
			//Init Frame Details
			this.setLocationRelativeTo(null);
			this.setResizable(false);
			this.setSize(WITDH, HEIGTH);
			this.setTitle("Add Student");
			
			//Add Panel to Frame and set Panel layout
			this.add(mainPanel);
			mainPanel.setLayout(new GridLayout(0,2));
			
			//Add labels, text fields, and button
			mainPanel.add(firstNameLabel);
			mainPanel.add(firstNameTextField);
			
			mainPanel.add(lastNameLabel);
			mainPanel.add(lastNameTextField);
			
			mainPanel.add(IDLabel);
			mainPanel.add(IDTextField);
			
			mainPanel.add(studentNoLabel);
			mainPanel.add(studentNoTextField);
			
			mainPanel.add(statusLabel);
			mainPanel.add(statusComboBox);
			
			mainPanel.add(facultyLabel);
			mainPanel.add(facultyComboBox);
			
			mainPanel.add(saveButton);
			mainPanel.add(cancelButton);
			
			
			saveButton.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
						jButtonSaveActionPerformed(evt);
	            }
	        });
			
			cancelButton.addActionListener(new java.awt.event.ActionListener() {
	            public void actionPerformed(java.awt.event.ActionEvent evt) {
						jButtonCancelActionPerformed(evt);
	            }
	        });
		}
		catch(Exception e){
			e.printStackTrace();
		}
	}
	
	private void jButtonCancelActionPerformed(java.awt.event.ActionEvent evt){
		parent.setVisible(true);
		this.dispose();
	}
	
	private void jButtonSaveActionPerformed(java.awt.event.ActionEvent evt){
		try{
			//Check ID Length bigger than 13
			if(IDTextField.getText().length() > 13)
				throw new IDException("IDLengthBig");
			
			//Check ID Length Smaller than 13
			if(IDTextField.getText().length() < 13)
				throw new IDException("IDLengthSmall");
			
			//Check First ID Digit is 1 or 2
			if(Integer.parseInt(IDTextField.getText().substring(0,1)) == 0 || Integer.parseInt(IDTextField.getText().substring(0,1)) > 2)
				throw new IDException("FirstIDDigit");
			
			//Check Month of Birth is smaller or equal with 12
			if(Integer.parseInt(IDTextField.getText().substring(3,5)) > 12 )
				throw new IDException("BirthMonth");
			
			//Check Day of Birth is smaller or equal with 21
			if(Integer.parseInt(IDTextField.getText().substring(5,7)) > 31 )
				throw new IDException("BirthDay");
			
			//Create new Student Class for creating XML File
			Student stud = new Student();
			stud.setFirstName(firstNameTextField.getText());
			stud.setLastName(lastNameTextField.getText());
			stud.setCNP(IDTextField.getText());
			stud.setFaculty(facultyComboBox.getSelectedIndex());
			
			//Student Status
			stud.setStatus(statusComboBox.getSelectedItem().toString());
			
			//Student Number
			stud.setStudentNo(Integer.parseInt(studentNoTextField.getText()));
			
			//Construct values array and fields array to pass to insertMethod 
			String values[] = stud.getValues();
			String fields[] = stud.getFields();
			
			//Get UMSDB Instance
			UMSDB db = UMSDB.getInstance();
			
			db.insertMethod("student", fields, values);			
			
			//Create an XMLSerializer object to serialize stud Object to file
//			XMLSerializer serializer = new XMLSerializer();
//			serializer.write(stud, "E:/Workspace/UMS/Student.xml");
			
			//Tell the user that the operation was successful
			JOptionPane pane =
			new JOptionPane("Student Succesfully Added", JOptionPane.INFORMATION_MESSAGE, JOptionPane.DEFAULT_OPTION);
			JDialog dialog = pane.createDialog(null, "Success!");
			dialog.setVisible(true);
			
		}
		catch(IDException IDE){
			JOptionPane pane =
			new JOptionPane(IDE.getMessage(), JOptionPane.ERROR_MESSAGE, JOptionPane.DEFAULT_OPTION);
			JDialog dialog = pane.createDialog(null, "Error!");
			dialog.setVisible(true);
		}
		
		catch(NumberFormatException nfe){
			JOptionPane pane =
			new JOptionPane("ID and Student Number Cannot Be Made of Letters!", JOptionPane.ERROR_MESSAGE, JOptionPane.DEFAULT_OPTION);
			JDialog dialog = pane.createDialog(null, "Error!");
			dialog.setVisible(true);
		}
		catch(Exception e){
			e.printStackTrace();
			JOptionPane pane =
			new JOptionPane(e.getMessage(), JOptionPane.ERROR_MESSAGE, JOptionPane.DEFAULT_OPTION);
			JDialog dialog = pane.createDialog(null, "Error!");
			dialog.setVisible(true);
		}
	}
}
